#coding:utf-8
'''
* coder  : dzlua
* email  : 505544956@qq.com
* module : python
* path   : lcdgdys
* file   : run.py
* time   : 2018-01-11 11:37:23
'''
#--------------------#
import sys, os, codecs, re, time
sys.path.append('../module/')
#--------------------#
from dzlua import dzlua
from spider import Spider
from bs4 import BeautifulSoup
#--------------------#

#--------------------#
cfg = {
    'tb': 'novel',
    'step': 50,
    'zh': {}
}
#--------------------#

#--------------------#
def db_add(sp, name, href):
    sql = "INSERT INTO " + cfg['tb'] + \
        " (name, href)" \
        " VALUES(%s,%s);"
    param = ( name, href )
    sp.execute(sql, param)
#----------#
def db_list(sp):
    sql = "SELECT id,name,href,last_href FROM %s;" % cfg['tb']
    resp = sp.select(sql)
    return resp
#----------#
def db_get(sp, id):
    sql = "SELECT id,name,href,last_href FROM %s WHERE id=%s;" % (
        cfg['tb'], id)
    for info in sp.select(sql):
        return info
#----------#
def db_save_last_href(sp, href):
    pass
#--------------------#

#--------------------#
def show_novel(sp, pre_url, url, next_url, title, content):
    idxs = range(cfg['step'], len(content) + cfg['step'], cfg['step'])
    if len(idxs) <= 0:
        return
    #
    def show_idx(idx):
        end = idxs[idx]
        begin = end - cfg['step']
        print content[begin-1:end]
    #
    last_idx = 0
    show_idx(last_idx)
    #
    while True:
        input = dzlua.getch().upper()
        if input == "Q":
            dzlua.clear()
            break
        if input == "P":
            last_idx -= 1
            if last_idx < 0:
                sp.put(cfg['handle_info'], pre_url)
                break
            else:
                show_idx(last_idx)
        if input == "N":
            last_idx += 1
            if last_idx >= len(idxs):
                sp.put(cfg['handle_info'], next_url)
                break
            else:
                show_idx(last_idx)
        if input == "C":
            dzlua.clear()
#--------------------#

#--------------------#
def handle_info(sp, url, resp, args):
    host = sp.url_host(url)
    if not resp:
        sp.prt('handle_info_error : no response. url: %s' % url)
        return
    soup = BeautifulSoup(resp, "lxml")
    div = soup.find('div', id="content")
    if not div:
        sp.prt('handle_info_error : no content. url: %s' % url)
        return
    #
    content = sp.del_empty_line(sp.get_strings(div))
    pre_url = None
    next_url = None
    title = ''
    #
    h1 = soup.find('h1')
    if h1:
        title = sp.del_empty_line(sp.get_strings(h1))
    #
    div = soup.find('div', class_="page_chapter")
    if div:
        for a in div.find_all('a'):
            if a.text == u'下一章':
                next_url = sp.url_join(host, a.get('href'))
            elif a.txt == u'上一章':
                pre_url = sp.url_join(host, a.get('href'))
    #
    show_novel(sp, pre_url, url, next_url, title, content)
#--------------------#

#--------------------#
def app_open(sp, info):
    last_href = info[3] or info[2]
    if not last_href:
        return False
    sp.put(handle_info, last_href)
    return True
#----------#
def app_list(sp):
    dzlua.clear()
    sp.prt('----- List ------')
    sp.prt('0. Back')
    #
    for info in db_list(sp):
        sp.prt('%s. %s %s' % (info[0], info[1], info[2]))
    #
    sp.prt('Input: ')
    input = dzlua.getch().upper()
    if input == '0':
        app_show_cmd(sp)
    else:
        data = db_get(sp, input)
        if not data:
            app_list(sp)
        else:
            app_open(sp, data)
#----------#
def app_add(sp):
    dzlua.clear()
    sp.prt('----- Add ------')
    name = raw_input('Input name: ')
    href = raw_input('Input href: ')
    db_add(sp, name, href)
    app_list(sp)
#----------#
def app_show_cmd(sp):
    dzlua.clear()
    sp.prt('----- Welcome ------')
    sp.prt('1. Add')
    sp.prt('2. List')
    sp.prt('3. Exit')
    sp.prt('Input: ')
    input = dzlua.getch().upper()
    if input == '1':
        app_add(sp)
    elif input == '2':
        app_list(sp)
    elif input == '3':
        return
    else:
        app_show_cmd(sp)
#--------------------#

#--------------------#
cfg['handle_info'] = handle_info
#--------------------#

#--------------------#
sp = Spider('localhost', 'dzlua', 'dzlua', 'dzlua', threads=1)
#
sql = "CREATE TABLE IF NOT EXISTS " + cfg['tb'] + \
    " (id INT AUTO_INCREMENT PRIMARY KEY," \
    " name TEXT," \
    " href TEXT," \
    " last_href TEXT )" \
    " DEFAULT CHARSET=utf8mb4;"
sp.execute(sql)
app_show_cmd(sp)
sp.wait()
sp.close()
#--------------------#
